package com.company.huisuo.base

import android.app.Activity
import android.app.Dialog
import android.graphics.Bitmap
import android.graphics.Canvas
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.animation.AnimationUtils
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.viewbinding.ViewBinding
import com.company.huisuo.R
import com.company.huisuo.ext.dp2px
import com.company.huisuo.utils.BlurUtil

/**
 * 带毛玻璃效果的Dialog基类
 * 支持延伸至状态栏，支持从右侧弹出，自动适配子类布局宽度
 */
abstract class BaseBlurDialog<VB : ViewBinding>(
    private val activity: Activity, private val touchOutEvent: (() -> Unit)? = null
) : Dialog(activity, R.style.BlurDialogStyle) {

    protected lateinit var mBinding: VB
    private var blurBgView: ImageView? = null
    private var contentContainer: FrameLayout? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = getViewBinding()

        val rootView = createDialogLayout()
        setContentView(rootView)

        setupWindow()
        applyBlurBackground()
        setupClickListener()
        initView()
        applySlideInAnimation()
    }

    /**
     * 创建Dialog布局
     */
    private fun createDialogLayout(): View {
        val rootLayout = FrameLayout(context).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
            )
            fitsSystemWindows = false
        }

        // 半透明蒙层（左侧区域）
        val maskView = View(context).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
            )
            setBackgroundColor(0x40000000)
        }
        rootLayout.addView(maskView)

        // 获取子类布局的宽度
        val childWidth = getContentWidth()

        // 内容容器
        contentContainer = FrameLayout(context).apply {
            val params = FrameLayout.LayoutParams(
                childWidth, ViewGroup.LayoutParams.MATCH_PARENT
            )
            params.gravity = Gravity.END
            layoutParams = params
        }

        // 边框层（最底层，不裁剪）
        val borderView = View(context).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
            )
            setBackgroundResource(R.drawable.bg_blur_dialog_content)
        }
        contentContainer?.addView(borderView)

        // 内容层容器（带圆角裁剪，不包含边框）
        val innerContainer = FrameLayout(context).apply {
            val params = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
            ).apply {
                leftMargin = 2.dp2px()
            }
            layoutParams = params
            clipToOutline = true
            outlineProvider = android.view.ViewOutlineProvider.BACKGROUND
            setBackgroundResource(R.drawable.bg_blur_dialog_inner)
        }

        // 模糊背景层（只在内容容器内）
        blurBgView = ImageView(context).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
            )
            scaleType = ImageView.ScaleType.CENTER_CROP
            alpha = 0.8f
        }
        innerContainer.addView(blurBgView)

        // 用户内容
        innerContainer.addView(
            mBinding.root, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
        )

        contentContainer?.addView(innerContainer)
        rootLayout.addView(contentContainer)

        return rootLayout
    }

    /**
     * 获取内容宽度（从子类布局的根视图LayoutParams读取）
     */
    private fun getContentWidth(): Int {
        val rootLayoutParams = mBinding.root.layoutParams
        return if (rootLayoutParams != null && rootLayoutParams.width > 0) {
            rootLayoutParams.width
        } else {
            // 如果没有设置宽度，使用默认值500dp
            500.dp2px()
        }
    }

    /**
     * 设置窗口属性，支持延伸至状态栏
     */
    private fun setupWindow() {
        window?.apply {
            decorView.systemUiVisibility =
                (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                attributes.layoutInDisplayCutoutMode =
                    WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
            }

            setLayout(
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT
            )
            setGravity(Gravity.CENTER)

            clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
            addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN)
            addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                setDecorFitsSystemWindows(false)
            }
        }
    }

    /**
     * 设置点击事件，点击外部关闭Dialog
     */
    private fun setupClickListener() {
        (contentContainer?.parent as? ViewGroup)?.setOnClickListener {
            if (touchOutEvent == null) {
                dismiss()
            } else {
                touchOutEvent.invoke()
            }
        }
        contentContainer?.setOnClickListener {
            // 阻止事件传递，点击内容区域不关闭
        }
    }

    /**
     * 应用模糊背景效果（只模糊内容区域对应的部分）
     */
    private fun applyBlurBackground() {
        try {
            val screenshot = captureScreen()
            screenshot?.let { fullBitmap ->
                // 计算内容区域在屏幕上的位置
                val contentWidth = getContentWidth()
                val screenWidth = fullBitmap.width
                val startX = screenWidth - contentWidth

                // 裁剪出内容区域对应的背景
                val croppedBitmap = Bitmap.createBitmap(
                    fullBitmap,
                    startX.coerceAtLeast(0),
                    0,
                    contentWidth.coerceAtMost(screenWidth),
                    fullBitmap.height
                )

                // 对裁剪后的区域进行模糊
                val blurredBitmap = BlurUtil.blur(context, croppedBitmap, 25f)
                blurBgView?.setImageBitmap(blurredBitmap)

                croppedBitmap.recycle()
                fullBitmap.recycle()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 截取当前屏幕
     */
    private fun captureScreen(): Bitmap? {
        return try {
            val rootView = activity.window.decorView.rootView
            val bitmap = Bitmap.createBitmap(
                rootView.width, rootView.height, Bitmap.Config.ARGB_8888
            )
            val canvas = Canvas(bitmap)
            rootView.draw(canvas)
            bitmap
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 应用从右侧滑入动画
     */
    private fun applySlideInAnimation() {
        contentContainer?.let { container ->
            val animation = AnimationUtils.loadAnimation(context, R.anim.slide_in_right)
            container.startAnimation(animation)
        }
    }

    /**
     * 重写dismiss，添加滑出动画
     */
    override fun dismiss() {
        contentContainer?.let { container ->
            val animation = AnimationUtils.loadAnimation(context, R.anim.slide_out_right)
            animation.setAnimationListener(object : android.view.animation.Animation.AnimationListener {
                override fun onAnimationStart(animation: android.view.animation.Animation?) {}

                override fun onAnimationEnd(animation: android.view.animation.Animation?) {
                    superDismiss()
                }

                override fun onAnimationRepeat(animation: android.view.animation.Animation?) {}
            })
            container.startAnimation(animation)
        } ?: superDismiss()
    }

    /**
     * 调用父类的dismiss
     */
    private fun superDismiss() {
        super.dismiss()
    }

    /**
     * 获取ViewBinding实例（子类实现）
     */
    abstract fun getViewBinding(): VB

    /**
     * 初始化视图（子类实现）
     */
    abstract fun initView()
}
